<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭"
  >
    <a-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
      <a-col :md="24" :sm="24" @keyup.enter.native="loadData">
          <a-card :bordered="false">
            园区名称:
          <a-input
            :style="{width:'250px',marginBottom:'15px'}"
            placeholder="请输入"
            v-model="queryParam.parkName"
          ></a-input>
            园区级别:
            <j-search-select-tag
              :style="{width:'250px',marginBottom:'15px'}"
              placeholder="请输入"
              dict="tb_park_level"
              v-model="queryParam.parkLevel"
              ></j-search-select-tag>
            <a-button type="primary" @click="loadData" style="margin-left: 20px" icon="search">查询</a-button>
          <a-button @click="searchReset(1)" style="margin-left: 20px" icon="redo">重置</a-button>
          <a-table
            ref="table"
            :scroll="scrollTrigger"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            :loading="loading"
            @change="handleTableChange">
            <!-- 字符串超长截取省略号显示-->
            <span slot="component" slot-scope="text">
              <j-ellipsis :value="text"/>
            </span>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </j-modal>
</template>

<script>
import {filterObj} from '@/utils/util'
import {getAction} from "../../../api/manage";

export default {
  name: 'SelectParkModal',
  components: {},
  props: ['modalWidth', 'multi', 'userIds', 'sign'],
  data() {
    return {
      queryParam: {
        name: "",
      },
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
          customCell: (record, index) => {
            let that = this;
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.selectionRows = [];
                    that.selectionRows.push(record);
                  }
                }
              }
            }
          },
          {
            title:'园区名称',
            align:"center",
            dataIndex: 'parkName',
            scopedSlots: {customRender: 'component'},
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.selectionRows = [];
                    that.selectionRows.push(record);
                  }
                }
              }
            }
          },
          {
            title:'环保负责部门',
            align:"center",
            dataIndex: 'epDepart',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.selectionRows = [];
                    that.selectionRows.push(record);
                  }
                }
              }
            }
          },
          {
            title:'环保负责人',
            align:"center",
            dataIndex: 'epPerson',
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.selectionRows = [];
                    that.selectionRows.push(record);
                  }
                }
              }
            }
          },
          {
            title:'园区级别',
            align:"center",
            dataIndex: 'parkLevel_dictText',
            scopedSlots: {customRender: 'component'},
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.selectionRows = [];
                    that.selectionRows.push(record);
                  }
                }
              }
            }
          },
          {
            title:'基本信息是否完善',
            align:"center",
            dataIndex: 'basicIsPerfect_dictText',
            scopedSlots: {customRender: 'component'},
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.selectionRows = [];
                    that.selectionRows.push(record);
                  }
                }
              }
            }
          },
          {
            title:'环保手续是否填写',
            align:"center",
            dataIndex: 'formalitiesIsPerfect_dictText',
            scopedSlots: {customRender: 'component'},
            customCell: (record, index)=> {
              let that=this;
              return {
                on: {
                  click: () => {
                    that.selectedRowKeys = [];
                    that.selectedRowKeys.push(record.id);
                    that.selectionRows = [];
                    that.selectionRows.push(record);
                  }
                }
              }
            }
          },

        ],
        scrollTrigger: {},
        dataSource: [],
        selectedRowKeys: [],
        selectUserRows: [],
        selectUserIds: [],
        title: '选择园区',
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        visible: false,
        form: this.$form.createForm(this),
        loading: false,
        url: {
          list: "/api/hmhb/analysis/home/page/chargeParkList",
          parkList:"/api/hmhb/park/tbHmhbPark/pageList",
        },
      }
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true ? 'checkbox' : 'radio';
      }
    },
    watch: {
      userIds: {
        immediate: true,
        handler() {
          this.initUserNames()
        }
      },
    },
    created() {
      // this.initialUrl();
      // 该方法触发屏幕自适应
      this.resetScreenSize();
      this.loadData()
    },
    methods: {
      // initialUrl(){
      //   this.url.list = '/api/hmhb/park/tbHmhbPark/list?bpmStatus=3';
      // },
      open(){
        console.log(this.modalWidth)
        this.visible = true;
        this.loadData();
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        console.log(selectedRowKeys,'selectedRowKeys')
        console.log(selectionRows,'selectionRows')
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      initUserNames() {
        if (this.userIds) {
          // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
          // let values = this.userIds.split(',') + ','
          // this.initialUrl()
          // getAction(this.url.list, {
          //   id: values,
          //   pageNo: 1,
          //   pageSize: values.length
          // }).then(res => {
          //   if (res.success) {
          //     let selectedRowKeys = []
          //     let names = []
          //     res.result.records.forEach(user => {
          //       names.push(user['parkName'])
          //       selectedRowKeys.push(user['id'])
          //     })
          //     this.selectedRowKeys = selectedRowKeys
          //     this.$emit('initComp', names.join(','))
          //   }
          // })
        } else {
          // JSelectUserByDep组件bug issues/I16634
          this.$emit('initComp', '')
        }
      },
      //首页回显数据
      initPark(parkId) {
        console.log(parkId,'园区id')
        getAction(this.url.parkList, {
          id: parkId,
          pageNo: 1,
          pageSize: 1
        }).then(res => {
          if (res.success) {
            console.log(res.result)
            let selectedRowKeys = []
            let names = []
            res.result.records.forEach(user => {
              names.push(user['parkName'])
              selectedRowKeys.push(user['id'])
            })
            this.selectedRowKeys = selectedRowKeys
          }
        })
      },
      async loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        this.loading = true
        // let params = this.getQueryParams()//查询条件
        // getAction(this.url.list, params).then(res => {
        //   if (res.success) {
        //     this.dataSource = res.result.records || res.result
        //     if (res.result.total) {
        //       this.ipagination.total = res.result.total
        //     } else {
        //       this.ipagination.total = 0
        //     }
        //     //判断是否当前页没有数据且不为第一页
        //     if(this.dataSource.length==0&&this.ipagination.current!=1){
        //       this.ipagination.current=this.ipagination.current-1
        //       this.loadData(this.ipagination.current-1);
        //     }
        //   }
        // }).finally(() => {
        //   this.loading = false
        // })
      },
      // 触发屏幕自适应
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.scrollTrigger = {x: 800};
        } else {
          this.scrollTrigger = {};
        }
      },
      showModal() {
        this.visible = true;
        this.initUserNames()
        this.loadData();
        this.form.resetFields();
      },
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        param.sign = this.sign;
        return filterObj(param);
      },
      getQueryField() {
        let str = 'id,';
        for (let a = 0; a < this.columns.length; a++) {
          str += ',' + this.columns[a].dataIndex;
        }
        return str;
      },
      searchReset(num) {
        let that = this;
        if (num !== 0) {
          that.queryParam = {};
          that.loadData(1);
        }
        that.selectedRowKeys = [];
        that.selectUserIds = [];
        that.selectedDepIds = [];
      },
      close() {
        this.searchReset(0);
        this.visible = false;
      },
      handleTableChange(pagination, filters, sorter) {
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc';
        }
        this.ipagination = pagination;
        this.loadData();
      },
      handleSubmit() {
        let that = this;
        this.getSelectUserRows();
        if(this.sign==2){
          if(that.selectUserIds ==null||that.selectUserIds =='' || that.selectUserIds ==undefined){
            that.$message.warning("请选择园区!");
          }else{
            that.$emit('gain',that.selectUserIds);
            that.close();
          }
        }else{
          that.$emit('ok', that.selectUserRows, that.selectUserIds);
          that.searchReset(0)
          that.close();
        }

      },
      //获取选择用户信息
      getSelectUserRows(rowId) {
        let dataSource = this.dataSource;
        let ids = "";
        this.selectUserRows = [];
        for (let i = 0, len = dataSource.length; i < len; i++) {
          if (this.selectedRowKeys.includes(dataSource[i].id)) {
            this.selectUserRows.push(dataSource[i]);
            ids = ids + "," + dataSource[i].id
          }
        }
        this.selectUserIds = ids.substring(1);
      },
      onSearch() {
        this.loadData(1);
      },
      modalFormOk() {
        this.loadData();
      }
    }
  }
</script>

<style scoped>
  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>